package cc.fs.zhihuapp.utils.myutils;

import android.media.MediaPlayer;
import android.preference.PreferenceActivity;
import android.text.TextUtils;
import android.util.Log;

import org.apache.http.Header;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

import cc.fs.zhihuapp.utils.Constants;
import cc.fs.zhihuapp.utils.RequestDealThread;

/**
 * Created by fostion on 2015/11/3.
 * 创建socket接受播放器发送过来的数据请求
 */
public class MyMediaPlayerProxy implements Runnable{

    private String TAG = "----MediaPlayerProxy-----";
    private ServerSocket serverSocket; //接受服务器
    private int port;//监听端口
    private Thread thread;//使用线程监听端口
    private boolean isRunning = true;//控制线程生命周期

    protected static MyRequestDealThread downloadThread;

    private void d(String msg){
        Log.d(TAG,msg);
    }

    public void init(){
        try {
            serverSocket = new  ServerSocket(port, 0, InetAddress.getByAddress(new byte[]{127, 0, 0, 1}));
            serverSocket.setSoTimeout(5000);
            port = serverSocket.getLocalPort();
            d(" 开启代理服务器成功，端口是 "+port);
        } catch (UnknownHostException e){
            d("开启代理服务器失败，未知host");
        } catch (IOException e) {
            d("开启代理服务器失败");
        }
    }

    public void start(){
        if(serverSocket == null){
            d("开启服务器失败，无法开始代理");
            return;
        }

        //开启线程监听操作
        thread = new Thread(this);
        thread.start();
    }

    public void stop() {
        isRunning = false;
        if(thread == null){
            return;
        }
        //挂起线程（这是java常用做法）
        thread.interrupt();
        try {
            //结束进程
            thread.join(5000);
        } catch (InterruptedException e) {
            d("---线程结束失败--");
        }
        d("---代理服务器停止代理---");
    }

    public String getProxyURL(String url) {
        return String.format("http://127.0.0.1:%d/%s", port, url);
    }

    @Override
    public void run() {
        d("--代理服务器已经开始监听---");
        while (isRunning){
            try {
                //接受连接socket的请求
                Socket client = serverSocket.accept();
                if(client == null){
                    continue;
                }

                d("--播放器发出了新的请求--");
                HttpUriRequest request  =  readRequest(client);
                if(request != null){//将请求解析后交给下载线程解析
                    d("--播放器发出请求解析成功，现在使用具体线程处理--");
                    downloadThread = new MyRequestDealThread(request, client);
                    downloadThread.start();
                }
            } catch (IOException e) {
                d("---代理服务器获取Player信息失败---");
            }

        }

    }

    /**
     * 读取socket client发出的请求
     */
    public HttpUriRequest readRequest(Socket client){
        HttpUriRequest request = null;
        int bytes_read;
        byte[] local_request = new byte[1024];
        String requestStr = "";

        try {
            //读取所有请求数据
           while ((bytes_read = client.getInputStream().read(local_request)) != -1){
               byte[] tmpBuffer = new byte[bytes_read];
               System.arraycopy(local_request, 0, tmpBuffer, 0, bytes_read);
               String str = new String(tmpBuffer);
               d(" 请求数据的头部信息-> "+str);
               requestStr = requestStr + str;
               if (requestStr.contains("GET") && requestStr.contains(Constants.HTTP_END)) {//必须读完所有请求才停止
                   break;
               }
           }
        } catch (IOException e) {
            d("--代理服务器读取请求信息失败!--");
            return request;
        }

        if(TextUtils.isEmpty(requestStr)){
            d("--接收到的头部信息是空--");
            return request;
        }

        // 将Request String组合为HttpUriRequest
        String[] requestParts = requestStr.split(Constants.LINE_BREAK);
        StringTokenizer st = new StringTokenizer(requestParts[0]);
        String method = st.nextToken();
        String uri = st.nextToken();

        d( "--代理服务器需要请求的数据--"+ uri.substring(1));
        request = new HttpGet(uri.substring(1));
        for (int i = 1; i < requestParts.length; i++) {
            int separatorLocation = requestParts[i].indexOf(":");
            String name = requestParts[i].substring(0, separatorLocation).trim();
            String value = requestParts[i].substring(separatorLocation + 1).trim();
            // 不添加Host Header，因为URL的Host为127.0.0.1
            if (!name.equals(Constants.HOST)) {//header 去掉 host:port
                request.addHeader(name, value);
            }
        }
        // 如果没有Range，统一添加默认Range,方便后续处理
        if (request.getFirstHeader(Constants.RANGE) == null) {
            request.addHeader(Constants.RANGE, Constants.RANGE_PARAMS_0);
        }

        Header header[] = request.getAllHeaders();
        for(int i=0;i<header.length;i++){
            d(" header:  name : "+header[i].getName()+ "  value: "+header[i].getValue());
        }

        return request;
    }
}
